// pages/dynamicPublish/dynamicPublish.js
import {
  addDynamic,
  dynamicTag,
  uploadSecurityImg
} from "../../api/index"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageArray: [],
    message: "",
    tagList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.queryDynamicTag();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },



  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.timer)
  },
  messageChange: function (e) {
    this.setData({
      message: e.detail.value
    })
  },
  uploadImg: async function () {
    let imgArray = this.data.imageArray

    const result = await uploadSecurityImg({
      count: 4
    })
    if (imgArray.length + result.length > 4) {
      return wx.showToast({
        title: '图片太多啦',
        icon: 'none'
      })
    }
    if (result.length !== 0) {
      let uploadArr = result.map(item => item.file)
      this.setData({
        imageArray: imgArray.concat(uploadArr)
      })
      console.log(uploadArr)
    }
  },
  submitDynamic: async function () {
    if(this.data.message===''){
      return wx.showToast({
        title: '请输入动态信息',
        icon:"none"
      })
    }
    // 诉求标签
    let dynamicTag = []
    this.data.tagList.forEach(item => {
      if (item.check) {
        dynamicTag.push(item)
      }
    })

    let result = await addDynamic({
      images: this.data.imageArray,
      message: this.data.message,
      dynamicTag: dynamicTag
    })
    if (result._id) {
      wx.showToast({
        title: '发布成功',
        mask: true,
        success: () => {
          this.timer = setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1000)
        }
      })
    }
    console.log(result)
  },

  // 查询诉求标签
  async queryDynamicTag() {

    let tagList = await dynamicTag()
    this.setData({
      tagList: tagList
    })


  },


  handleTag(e) {

    let index = e.currentTarget.dataset.index

    let tagList = this.data.tagList
    tagList[index].check = tagList[index].check ? false : true

    this.setData({
      tagList: tagList
    })


  },
  deleteImg(e){
    const index = e.currentTarget.dataset.index
    let imageArray = this.data.imageArray
    imageArray.splice(index,1)
    this.setData({
      imageArray:imageArray
    })
  }
})